<template>
  <div class="main" v-loading="loading" id="main" >
  <!-- <div class="main" v-loading="loading" id="main" @contextmenu.prevent="contextMenuHandler"> -->
    <!-- tab目录结构 -->
    <div class="breadCard">
      <div v-if="menuTabs.length > 1"><el-link @click="clickUpLevel()" type="primary">返回上一级</el-link><span class="icon-right">|</span></div>
      <div v-for="(i, index) in menuTabs" :key="index">
        <span>
          <el-link type="primary" @click="clickFolderLevel(index)"  v-if="index < menuTabs.length - 1">{{i.name}}</el-link>
          <span v-else :title="i.name" style="color: #666666;" >{{i.name}}</span>
        </span>
        <span class="icon-right" v-if="index < menuTabs.length - 1">></span>
      </div>
    </div>
    <!-- 页面展示内容 -->
    <div class="file-content">
      <!-- 全选按钮头部区域 -->
      <div class="checkTitle">
        <div>
          <el-checkbox v-model="checkAll" @change="handleCheckAllChange" :indeterminate="multipleSelection.length > 0 && multipleSelection.length < fileData.length">
            <span v-if="multipleSelection.length !== 0">已选中{{multipleSelection.length}}个文件/文件夹</span>
            <span>文件名</span>
          </el-checkbox>
        </div>
        <div v-if="multipleSelection.length === 0 && !isMenu">大小</div>
        <div v-if="multipleSelection.length === 0 && !isMenu">修改时间</div>
      </div>
      <!-- 方格展示 -->
      <div class="file-menu" v-if="isMenu">
        <div class="file-box" v-for="(i,index) in fileData" :key="index" :class="{inputChecked: i.checked}"
          @contextmenu.prevent="fileMenus(i)">
          <!-- 新加文件夹 -->
          <template v-if="i.isCreadte" class="addFile-box">
            <div class="fileimg" ><img :src="loadMenuImg(i)" alt=""></div>
            <input type="text" class="addInput" v-model="i.fileName">
            <span class="addBtn"><i class="el-icon-check" @click="saveNewFolder(i)"></i></span>
            <span class="addBtn" @click="cancelAdd(i)"><i class="el-icon-close"></i></span>
          </template>
          <template v-else>
            <input type="checkbox" @change.stop="checkedStyle(i, $event)" :checked="i.checked" class="el-icon-success">
            <div class="fileimg" @click="openFile(i)"><img :src="loadMenuImg(i)" alt=""></div>
            <div class="filename" @click="openFile(i)">{{i.fileName}}</div>
            <div v-if="!i.checked" class="menuTools">
              <i v-if="!i.isFolder" class="el-icon-view" title="在线浏览" @click="viewFile(i)"></i>
              <i v-if="!i.isFolder" class="el-icon-download" title="下载" @click="downloadFile(i)"></i>
            </div>
          </template>
        </div>
      </div>
      <!-- 列表展示 -->
      <div class="file-list" v-else>
        <dd v-for="(it,index) in fileData" :key="index" :class="{ddActive: it.checked}">
          <div>
            <el-checkbox v-model="it.checked" @change="checkedStyle(it)"></el-checkbox>
            <template v-if="it.isCreadte"  >
              <img class="listImg" :src="loadListImg(it)" alt="">
              <input type="text" class="addInput" v-model="it.fileName">
              <span class="addBtn" @click="saveNewFolder(it)"><i class="el-icon-check"></i></span>
              <span class="addBtn" @click="cancelAdd(it)"><i class="el-icon-close"></i></span>
            </template>
            <template v-else >
              <span>
                <img class="listImg" :src="loadListImg(it)" alt="">
                <span  v-if="it.isFolder" class="filename" @click="openFile(it)">{{it.fileName}}</span>
                <span  v-else class="filename" @click="viewFile(it)">{{it.fileName}}</span>
                <!-- 工具栏 -->
                <div class="tools">
                  <i v-if="!it.isFolder" class="el-icon-view" title="在线浏览" @click="viewFile(it)"></i>
                  <i v-if="!it.isFolder" class="el-icon-download" title="下载" @click="downloadFile(it)"></i>
                  <i v-if="authOpt === 'M'" class="el-icon-more" @click="showMore(it, $event)"></i>
                </div>
              </span>
            </template>
          </div>
          <div v-if="!it.isFolder">{{renderSize(it.fileSize)}}</div>
          <div v-else></div>
          <div>{{it.upLoadDate}}</div>
        </dd>
      </div>
    </div>
    <!-- 鼠标右键菜单列表 -->
    <rightMenu :visible.sync="show" @addFile="addFile"/>
    <!-- 更多菜单 -->
    <showMore :visible.sync="moreMenus" @rename="rename" @delNode="delNode"/>
  </div>
</template>
<script>
  import rightMenu from '@/pages/fileManage/fileSystem/rightMenu'
  import showMore from '@/pages/fileManage/fileSystem/showMore'
  import FolderEventBust from '@/eventbus/FolderEventBus.js'
  import {docFolderFileApi} from '@/api/business/businessApi'
  import { listImg, menuImg } from '@/utils/constants.js'
  import { fastDFSFileApi, onlinePreviewApi } from '@/api/file/fileApi.js'
  import { openDownloadFile } from '@/utils/devUtils' // downFile
  import moment from 'moment'

  export default {
    components: {
      rightMenu,
      showMore
    },
    props: {
      // 业务数据的id
      bizId: {
        type: String,
        default: '1'
      },
      // 业务数据的id
      bizType: {
        type: String,
        default: ''
      },
      // 业务数据名称
      bizTypeName: {
        type: String,
        default: ''
      },
      isMenu: {
        type: Boolean,
        default: true
      },
      fileData: {
       type: Array,
       default: function () {
          return [{
            img: '',
            fileName: '',
            fileSize: '',
            upLoadDate: '',
            checked: false,
            id: '',
            isCreadte: false,
            isFolder: true
          }]
        }
      },
      // fileData: {
      //   type: Array,
      //   default: function () {
      //     return []
      //   }
      // },
      // 是否创建新文件
      isCreadte: {
        type: Boolean,
        default: true
      },
      // 操作权限 M:管理 v:查看
      authOpt: {
        type: String,
        default: 'V'
      }
    },
    data () {
      return {
        loading: false,
        target: document.getElementsByClassName('right-menu'),
        triggerHideFn: function triggerHideFn () {},
        show: false,
        multipleSelection: [],
        muenuMode: {
            id: '',
            name: '',
            path: ''
        },
        menuTabs: [],
        checkAll: false,
        target1: document.getElementsByClassName('more-menus'),
        moreMenus: false,
        item: {},
        folderPId: this.bizId,
        fileMode: {
            img: '',
            fileName: '',
            fileSize: '',
            upLoadDate: '', // 上传时间
            checked: false,
            id: '',
            isCreadte: false,
            isFolder: true
        },
        addFolderFg: false
      }
    },
    watch: {
      folderPId: function (val) {
        if (val !== this.bizType) {
          this.$emit('selectFolder', this.folderPId)
        }
      },
      // bizId (val) {
      //   this.folderPId = val
      //   this.initData()
      // },
      bizId: {
        handler (v) {
           this.folderId = v
           this.initData()
        },
        immediate: true
      }
    },
    created () {
        FolderEventBust.$on('clickFolder', (folderId, folderName) => {
            this.folderPId = folderId
            this.menuTabs = []
            let newMenu = JSON.parse(JSON.stringify(this.muenuMode))
            newMenu.id = folderId
            newMenu.name = folderName
            this.menuTabs.push(newMenu)
            this.loadFolderData(this.folderPId)
        })
        this.initData()
    },
    mounted () {
    },
    methods: {
      /// <summary>
      /// 格式化文件大小的JS方法
      /// </summary>
      /// <param name="filesize">文件的大小,传入的是一个bytes为单位的参数</param>
      /// <returns>格式化后的值</returns>
      renderSize (value) {
          if (value === null) {
              return '0 Bytes'
          }
          let unitArr = ['Bytes', 'KB', 'MB', 'GB', 'TB']
          let index = 0
          let srcsize = parseFloat(value)
          index = Math.floor(Math.log(srcsize) / Math.log(1024))
          let size = srcsize / Math.pow(1024, index)
          size = size.toFixed(2) // 保留的小数位数
          return size + ' ' + unitArr[index]
      },
      // 初始化数据
      initData () {
        this.menuTabs = []
        let newMenu = JSON.parse(JSON.stringify(this.muenuMode))
        newMenu.id = this.bizId
        newMenu.name = this.bizTypeName
        this.menuTabs.push(newMenu)
        this.loadFolderData(this.bizId)
      },
      // 重新加载列表数据
      reloading () {
        this.loadFolderData(this.folderPId)
      },
      // 改变文件夹事件
      changFolerEvent () {
         FolderEventBust.$emit('changFolerEvent')
      },
      // 加载文件夹下内容
      loadFolderData (folderId) {
        this.loading = true
        let _this = this
        docFolderFileApi.getFolderListByFolderId(this.bizType, folderId).then(ret => {
            _this.fileData = []
            _this.folderPId = folderId
            _this.item = ret.data.map(file => {
              let newfile = JSON.parse(JSON.stringify(this.fileMode))
              newfile.id = file.id
              newfile.fileName = file.nodeName
              newfile.img = file.fileType
              newfile.fileSize = file.fileSize
              newfile.attachmentId = file.attachmentId
              newfile.upLoadDate = moment(file.createTime).format('YYYY-MM-DD')
              // 1：文件夹 2：文件
              newfile.isFolder = file.nodeType === '1'
              _this.fileData.push(newfile)
            })
            // 排序
            _this.fileData = _this.fileData.sort((f1, f2) => {
              if (f1.isFolder === f2.isFolder) {
                return f1.fileName - f1.fileName
              } else if (f1.isFolder) {
                return false
              } else if (f2.isFolder) {
                return true
              }
            })
            this.loading = false
          })
      },
      // 点击文件夹
      openFile (folder) {
        if (folder.isFolder) {
            let newMenu = JSON.parse(JSON.stringify(this.muenuMode))
            newMenu.id = folder.id
            newMenu.name = folder.fileName
            this.menuTabs.push(newMenu)
            this.loadFolderData(folder.id)
        }
      },
      // 返回上一层
      clickUpLevel () {
        this.menuTabs.pop()
        let upMenu = this.menuTabs[this.menuTabs.length - 1]
        this.loadFolderData(upMenu.id)
      },
      // 点击文件层
      clickFolderLevel (levelIndex) {
        this.menuTabs = this.menuTabs.slice(0, levelIndex + 1)
        let upMenu = this.menuTabs[this.menuTabs.length - 1]
        this.loadFolderData(upMenu.id)
      },
      // 新增文件夹
      addFile () {
        let flag = false
        this.fileData.map(_ => { if (_.isCreadte) { flag = true } })
        if (flag) return this.onfocus()
        let newfile = JSON.parse(JSON.stringify(this.fileMode))
        newfile.isCreadte = true
        newfile.fileName = '新建文件夹'
        this.fileData.splice(0, 0, newfile)
        this.onfocus()
      },
      // 同一目录下，名字重复检查
      recheckName (fileName) {
        let fObj = this.fileData.find(item => {
          return !item.isCreadte && item.fileName === fileName
        })
        if (fObj != null) {
          this.error('“' + fileName + '”名字重复。')
          return true
        }
        return false
      },
      // 保存文件夹
      saveNewFolder (folder) {
        if (this.recheckName(folder.fileName)) {
          return
        }
        this.loading = true
        // 新增
        if (folder.id === '') {
          docFolderFileApi.saveNewFolder(this.folderPId, {
              nodeName: folder.fileName,
              bizType: this.bizType
            }).then(ret => {
              this.success('保存成功。')
              folder.isCreadte = false
              this.loading = false
              this.changFolerEvent()
              this.loadFolderData(this.folderPId)
            })
        } else {
           docFolderFileApi.updateFolderInfo({
             id: folder.id,
             nodeName: folder.fileName
           }).then(ret => {
              this.success('保存成功。')
              folder.isCreadte = false
              this.loading = false
              this.changFolerEvent()
            })
        }
      },
      // 新增文件后聚焦input框
      onfocus () {
        this.$nextTick(() => {
          let e = document.getElementsByClassName('addInput')
          e[0].select()
        })
      },
      // 右键事件事件处理
      // contextMenuHandler (e) {
      //   this.show = false
      //   this.target[0].style.top = e.clientY + 'px'
      //   this.target[0].style.left = e.clientX + 'px'
      //   this.show = true
      //   document.addEventListener('click', this.bindHideEvents)
      // },
      // 绑定隐藏菜单事件
      bindHideEvents () {
        console.log('bindHideEvents')
        this.show = false
        document.removeEventListener('click', this.bindHideEvents)
      },
      // 鼠标按压事件处理器
      clickDocumentHandler () {
        this.show = false
      },
      // 加载菜单不同的图片
      loadMenuImg (file) {
       if (file.isFolder) {
          return menuImg['Folder']
        } else {
          return menuImg[file.img]
        }
      },
      loadListImg (file) {
        if (file.isFolder) {
          return listImg['Folder']
        } else {
          return listImg[file.img]
        }
      },
     // 取消新增文件夹
      cancelAdd (data) {
        // 有id，则修改文件名
        if (data.id) {
          data.isCreadte = false
        } else {
          // 新增文件夹
          this.fileData.map((_, index) => {
            if (this.isCreadte) {
              this.isCreadte = false
            }
            if (_.isCreadte) {
              this.fileData.splice(index, 1)
            }
          })
        }
      },
      // addFile () {
      //   this.$emit('addFile', true)
      // },
      chakan () {
        console.log('fileData', this.fileData)
      },
      // 选中时加载box边框样式
      checkedStyle (data, e) {
        if (e) data.checked = e.target.checked
        // 将选中数据存储
        if (data.checked) {
          this.multipleSelection.push(data)
        } else {
          this.multipleSelection.map((_, index) => {
            if (_.id === data.id) {
              this.multipleSelection.splice(index, 1)
            }
          })
        }
        this.checkAll = this.fileData.length === this.multipleSelection.length
        if (this.multipleSelection.length !== 0) this.$emit('selectData', this.multipleSelection)
      },
      // 文件上点击鼠标右键
      fileMenus (data) {
        console.log('fileMenus', data)
      },
      // 方格展示时，全选事件
      handleCheckAllChange (val) {
        this.multipleSelection = val ? JSON.parse(JSON.stringify(this.fileData)) : []
        this.fileData.map(_ => { _.checked = val })
        this.$emit('selectData', this.multipleSelection)
      },
      // 展示更多菜单
      showMore (data, e) {
        e.cancelBubble = true
        this.moreMenus = false
        this.target1[0].style.top = e.clientY + 15 + 'px'
        this.target1[0].style.left = e.clientX - 40 + 'px'
        this.moreMenus = true
        this.item = data
        document.addEventListener('click', this.hideShowMore)
      },
      hideShowMore () {
        this.moreMenus = false
        document.removeEventListener('click', this.hideShowMore)
      },
      // 修改item的名字
      rename () {
        // 显示input框
        this.item.isCreadte = true
        this.moreMenus = false // 关闭弹框
        // this.$emit('addFile') // 让input聚焦
      },
      // 删除文件目录
      delNode () {
        let _this = this
          this.$confirm('此操作会删除该条数据，是否继续？', '提示', {
            type: 'warning'
          }).then(() => {
            this.loading = true
            docFolderFileApi.deleteFolder(this.item.id).then(ret => {
                _this.success('删除成功。')
                if (this.item.isFolder) {
                  this.changFolerEvent()
                }
                _this.loadFolderData(_this.folderPId)
                _this.loading = false
            })
          })
      },
      // 批量删除
      delBatchNode () {
        let _this = this
        let isFolder = false
        let selectNodesId = this.multipleSelection.map(node => {
          if (!isFolder && node.isFolder) {
            isFolder = true
          }
          return node.id
        })
        if (!selectNodesId.length) {
          this.error('请勾选文件或文件夹')
          return ''
        } else {
          this.$confirm('此操作会删除选中的数据，是否继续？', '提示', {
            type: 'warning'
          }).then(() => {
              this.loading = true
              docFolderFileApi.deleteBatchNode({nodeIds: selectNodesId}).then(ret => {
                  _this.success('删除成功。')
                  _this.multipleSelection = []
                  if (isFolder) {
                  _this.changFolerEvent()
                  }
                  _this.loadFolderData(_this.folderPId)
                  _this.loading = false
              })
           })
        }
      },
      // 下载单个文件
      downloadFile (file) {
        fastDFSFileApi.downloadFile(file.attachmentId).then(res => {
            openDownloadFile(res)
        })
      },
      // 在线刘帆
      viewFile (file) {
       onlinePreviewApi.openViewFile(file.attachmentId)
      }
    }
  }
</script>
<style lang="scss">
  .main {
    width: 100%;
    height: calc(100% - 50px);
    font-size: 13px;
  }
  .main .breadCard {
    line-height: 16px;
    height: 18px;
    padding-left: 10px;
  }
  .main .breadCard > div {
    display: inline-block;
  }
  .main .breadCard .icon-right {
    width: 20px;
    display: inline-block;
    text-align: center;
    color: #c5d8f3;
  }
  .file-list, .file-menu{
    width: 100%;
    height: 100%;
  }
  .file-menu .file-box {
    width: 120px;
    height: 120px;
    float: left;
    margin: 2px 0 0 6px;
    text-align: center;
    border: 1px solid #fff;
    position: relative;
    cursor: pointer;
    color: #424e67;
  }
  .file-content .checkTitle {
    border-top-color: #fff;
    height: 36px;
    line-height: 36px;
    color: #888;
    overflow: hidden;
    border-bottom: 1px solid #f2f6fd;
    border-bottom: 1px solid #f2f6fd;
    box-sizing: border-box;
    .el-checkbox__label {
      padding-left: 18px;
    }
    & > div {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      // 文件名
      & > div:nth-child(1) {
        width: 60%;
        min-width: 460px;
        position: relative;
        padding: 0 0 0 14px;
        .listImg {
          vertical-align: middle;
          margin: 0 14px;
        }
      }
      & > div:nth-child(2) {
        width: 16%;
        color: #666666;
      }
      & > div:last-child {
        width: 23%;
        color: #666666;
      }
  }
  .file-menu .addInput {
    width: 56%;
  }
   .addInput {
    padding: 0 0 0 5px;
    width: 60%;
    height: 24px;
    border: 1px solid #C3EAFF;
    background: #fff;
    border-radius: 2px;
    display: inline-block;
    vertical-align: middle;
    margin: 0px 2px 2px -6px;
    color: #666;
  }
  .addInput:focus {
    outline: 0;
    box-shadow: 0 0 5px 0 #09AAFF;
  }
  .addBtn {
    color: #09AAFF;
    width: 20px;
    height: 20px;
    display: inline-block;
    border: 1px solid #09AAFF;
    text-align: center;
    position: relative;
    vertical-align: middle;
    margin-left: 4px;
    border-radius: 4px;
    cursor: pointer;
  }
  .addBtn i {
    position: absolute;
    top: 3px;
    left: 3px;
    font-size: 12px;
    font-weight: bolder;
  }
  .file-menu .addBtn {
    margin-left: 0;
  }
  .file-menu .addBtn:last-child {
    margin-left: 2px;
  }

  .file-box {
    .addFile-box {
      width: 140px;
    }
  }
  .file-box:hover {
    border: 1px solid #f1f5fa;
    border-radius: 5px;
    background: #f1f5fa;
  }
  .file-box .menuTools {
    color: #409EFF;
    font-size: 16px;
    position: absolute;
    top: 2px;
    right: 10px;
    display: none;
  }
  .file-box:hover .menuTools {
    display: block;
  }
  .file-box .fileimg {
    position: relative;
    margin: 24px auto 0;
    width: 60px;
    height: 60px;
    background-repeat: no-repeat;
    overflow: hidden;
    & > img {
      width: 46px;
    }
  }
  .file-box .filename {
    display: block;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    margin: 0px 5px 5px;
    font-size: 14px;
  }
  .file-box input[type="checkbox"] {
    position: absolute;
    top: 4px;
    left: 4px;
    width: 18px;
    height: 18px;
    appearance: none; /*清除复选框默认样式*/
    cursor: pointer;
    outline: none;
    display: none; /**默认不显示 */
  }
  .file-box:hover input[type="checkbox"] {
    display: block;
  }
  .file-box input[type="checkbox"]::before {
    font-size: 18px;
    color: #9FDFFF;
  }
  .file-box input[type="checkbox"]:hover::before {
    color: #7FD5FF;
  }
  /* 选中样式 */
  .inputChecked {
    background-color: #f1f5fa;
    border: 1px solid #90d8ff!important;
    border-radius: 5px;
  }
  .file-box input[type="checkbox"]:checked{
    display: block;
  }
  .file-box input[type="checkbox"]:checked::before {
    color: #00ACFF;
  }
  .listImg {
    vertical-align: top;
    margin-right: 14px;
  }
  // table展示文件夹
  .file-list {
    color: #424e67;
    dd {
      position: relative;
      height: 44px;
      line-height: 44px;
      border-bottom: 1px solid #f2f6fd;
      white-space: nowrap;
      text-overflow: ellipsis;
      background: #FFF;
      user-select: none;
      & > div {
        display: inline-block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      // 文件名
      & > div:nth-child(1) {
        width: 60%;
        min-width: 460px;
        position: relative;
        padding: 0 0 0 14px;
        .listImg {
          vertical-align: middle;
          margin: 0 14px;
        }
      }
      & > div:nth-child(2) {
        width: 16%;
        color: #666666;
      }
      & > div:last-child {
        width: 24%;
        color: #666666;
      }
    }
    .ddActive {
      background: #F4FBFF;
      border-color: #CBEDFF;
    }
    // 移动上去工具显示
    .tools {
      position: absolute;
      top: 0;
      right: 10px;
      display: none;
      & > i {
        cursor: pointer;
        font-size: 16px;
        margin-right: 10px;
        vertical-align: middle;
        color: #00ACFF;
      }
      & > .el-icon-more {
        position: relative;
      }
    }
    dd:hover {
      background: #F4FBFF;
      border-color: #CBEDFF;
    }
    dd:hover .tools {
      display: block;
    }
  }
  .filename {
    white-space: nowrap;
    cursor: pointer;
  }
  .file-list .filename:hover, .file-menu .filename:hover {
    color: #09AAFF;
  }

</style>
